package com.hifar.test.synctable8357.controller;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.fw.json.JsonUtils;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.fw.utils.lang.CollectionUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.test.synctable8357.pojo.SysInfoSyncTable8357;
import com.hifar.test.synctable8357.service.ISysInfoSyncTable8357Service;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.PageResult;
import com.hifar.sys.RequestConver;
import com.hifar.sys.SystemUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 双网同步-同步表 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-11-12 19:27:27
 */
@RestController
@RequestMapping("/api/busi/proj/SysInfoSyncTable8357Controller")
@Api(tags = "双网同步-同步表功能")
public class SysInfoSyncTable8357Controller {

    @Autowired
    private ISysInfoSyncTable8357Service sysInfoSyncTable8357Service;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "双网同步-同步表功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String,Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<SysInfoSyncTable8357> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        //queryWrapper.in("secret_level",SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
             Page<SysInfoSyncTable8357> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer)pageInfo.get("pageSize"));
             Page<SysInfoSyncTable8357> page1 = sysInfoSyncTable8357Service.page(page, queryWrapper);
             page1.getRecords().forEach(item->{
             });
             /*计算分页信息返回给前端*/
             PageResult pageResult = SystemUtil.parsePage(page, page1);
             return BusiResponse.OK(pageResult);
        }else {
             return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "双网同步-同步表功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<SysInfoSyncTable8357> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag","1");
        queryWrapper.orderByDesc("create_time");
        //queryWrapper.in("secret_level",SystemLoginUser.dataSecretSet);
        List<SysInfoSyncTable8357> list = sysInfoSyncTable8357Service.list(queryWrapper);
        list.forEach(item->{
        });
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        }else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }
    
    @PostMapping(value = "/queryRequireSyncTableIds")
    @ApiOperation(value = "双网同步-同步表功能:查询所有要同步的表的id")
    public BusiResponse queryRequireSyncTableIds(HttpServletRequest request) {
        QueryWrapper<SysInfoSyncTable8357> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag","1");
        queryWrapper.eq("status","1");
        queryWrapper.orderByDesc("create_time");
       
        List<SysInfoSyncTable8357> list = sysInfoSyncTable8357Service.list(queryWrapper);
        Set<String> idSet= list.stream().map(item->item.getId()).collect(Collectors.toSet());
        if (idSet != null && idSet.size() > 0) {
            return BusiResponse.OK(idSet);
        }else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }
    
    

    @PostMapping(value = "/add")
    @ApiOperation(value = "双网同步-同步表功能:新增")
    public BusiResponse add(@RequestBody SysInfoSyncTable8357 SysInfoSyncTable8357) {
    	
    	//如果存在则修改
		QueryWrapper<SysInfoSyncTable8357> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_name",StringUtils.trimNull(SysInfoSyncTable8357.getTableName()));
		SysInfoSyncTable8357 oneBean=sysInfoSyncTable8357Service.getOne(queryWrapper);
		if(oneBean!=null) {
			SysInfoSyncTable8357.setId(oneBean.getId());
		}else {
			SysInfoSyncTable8357.setId(IdUtils.uuid32());
		}
        sysInfoSyncTable8357Service.saveOrUpdate(SysInfoSyncTable8357);
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/addBySelectTableInfo")
    @ApiOperation(value = "双网同步-同步表功能:新增")
    public BusiResponse addBySelectTableInfo(@RequestBody String tableInfo) {
    	List<Map<String, Object>> selectList=	JsonUtils.toArray(tableInfo);
        System.out.println("====selectList========"+selectList);
        SysInfoSyncTable8357 SysInfoSyncTable8357=null;
        List<SysInfoSyncTable8357> dataList=new ArrayList<SysInfoSyncTable8357>();
    	for(Map<String, Object> oneMap:selectList) {
    		SysInfoSyncTable8357=new SysInfoSyncTable8357();
    		SysInfoSyncTable8357.setId(IdUtils.uuid32());
    		SysInfoSyncTable8357.setTableName(StringUtils.trimNull(oneMap.get("tableName")));
    		SysInfoSyncTable8357.setDescription(StringUtils.trimNull(oneMap.get("description")));
    		
    		//如果存在则修改
    		QueryWrapper<SysInfoSyncTable8357> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("table_name",StringUtils.trimNull(oneMap.get("tableName")));
            queryWrapper.eq("del_flag","0");
    		SysInfoSyncTable8357 oneBean=sysInfoSyncTable8357Service.getOne(queryWrapper);
    		if(oneBean!=null) {
    			SysInfoSyncTable8357.setId(oneBean.getId());
    		}
    		
    		dataList.add(SysInfoSyncTable8357);
    	}
    	sysInfoSyncTable8357Service.saveOrUpdateBatch(dataList);
    	
        return BusiResponse.ok("添加成功");
    }


    @PostMapping(value = "/saveConfigInfo")
    @ApiOperation(value = "双网同步-同步表功能:保存配置")
    public BusiResponse saveConfigInfo(@RequestBody String tableInfo) {
    	List<Map<String, Object>> selectList=	JsonUtils.toArray(tableInfo);
        System.out.println("====saveConfigInfo========"+selectList);
        SysInfoSyncTable8357 SysInfoSyncTable8357=null;
        List<SysInfoSyncTable8357> dataList=new ArrayList<SysInfoSyncTable8357>();
    	for(Map<String, Object> oneMap:selectList) {
    		SysInfoSyncTable8357=new SysInfoSyncTable8357();
    		SysInfoSyncTable8357.setId(StringUtils.trimNull(oneMap.get("id")));
    		SysInfoSyncTable8357.setStatus(StringUtils.trimNull(oneMap.get("status")));
    		dataList.add(SysInfoSyncTable8357);
    	}
    	sysInfoSyncTable8357Service.updateBatchById(dataList);
    	
        return BusiResponse.ok("保存配置成功");
    }
    
    
    @PostMapping(value = "/saveConfigInfoAll")
    @ApiOperation(value = "双网同步-同步表功能:保存所有配置")
    public BusiResponse saveConfigInfoAll(@RequestBody String tableInfo) {
    	Map<String, Object> selectMap=	JsonUtils.toMap(tableInfo);
    	
        System.out.println("====saveConfigInfo========"+selectMap);
        String idArg=StringUtils.trimNull(selectMap.get("id"));
        List<String> ids=CollectionUtils.valueOfList(idArg);
        
        //修改所有的数据为未选中，
        QueryWrapper<SysInfoSyncTable8357> queryWrapper = new QueryWrapper<>();
        SysInfoSyncTable8357 updateBean=new SysInfoSyncTable8357();
        updateBean.setStatus("2");
        queryWrapper.eq("del_flag","0");
        sysInfoSyncTable8357Service.update(updateBean,queryWrapper);
        
        //修改要选中的数据为选中状态
        SysInfoSyncTable8357 SysInfoSyncTable8357=null;
        List<SysInfoSyncTable8357> dataList=new ArrayList<SysInfoSyncTable8357>();
    	for(String id:ids) {
    		SysInfoSyncTable8357=new SysInfoSyncTable8357();
    		SysInfoSyncTable8357.setId(id);
    		SysInfoSyncTable8357.setStatus("1");
    		dataList.add(SysInfoSyncTable8357);
    	}
    	sysInfoSyncTable8357Service.updateBatchById(dataList);
    	
        return BusiResponse.ok("保存配置成功");
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "双网同步-同步表功能:编辑")
    public BusiResponse edit(@RequestBody SysInfoSyncTable8357 SysInfoSyncTable8357) {
        sysInfoSyncTable8357Service.updateById(SysInfoSyncTable8357);
        return BusiResponse.ok("编辑成功！");
    }




    @GetMapping("/queryById")
    @ApiOperation(value = "双网同步-同步表功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(value = "id") String id){
        SysInfoSyncTable8357 byId = sysInfoSyncTable8357Service.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }




    @PostMapping("/delete")
    @ApiOperation(value = "双网同步-同步表功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> id){
       // JSONObject jsonObject = JSON.parseObject(id);
        UpdateWrapper<SysInfoSyncTable8357> delete = new UpdateWrapper<>();
        delete.in("id",id);
        delete.set("del_flag","1");
        sysInfoSyncTable8357Service.update(delete);
        return BusiResponse.ok("删除成功！");
    }
   
        @PostMapping("/exportExcel")
	@ApiOperation(value = "双网同步-同步表功能:导出数据")
	public Object exportExcel(HttpServletRequest request) {
		Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
		if (pageInfo == null) {
			return BusiResponse.error("参数有误！");
		}
		BusiResponse export = sysInfoSyncTable8357Service.exportExcel(pageInfo);
		if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
			String encode = null;
			try {
				encode = URLEncoder.encode("双网同步-同步表.xlsx", "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Type", "application/vnd.ms-excel");
			headers.add("Access-Control-Expose-Headers", "Content-Disposition");
			headers.add("Content-Disposition", "filename=" + encode);
			return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
		}
		return export;
	}

	@PostMapping("/importExcel")
	@ApiOperation(value = "双网同步-同步表功能:导入excel数据")
	public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			return BusiResponse.error("文件为空！");
		} else {
			if (ExcelTemplateUtil.isExcelFile(file)) {
				return sysInfoSyncTable8357Service.importExcel(file);
			} else {
				return BusiResponse.error("请上传excel文件！");
			}
		}
	}
    

}